<template>
  <!-- 广告内容管理 -->
  <el-container>
    <el-header>
      <!-- //引入pagetitle组件 -->
      <Pagetitle :title="title1" :SecTitle="title2"></Pagetitle>
          </el-header
    >
        <el-main style="padding: 20px 0px"
      > 
      <!--这里是页面内容区域
		//这个区域的背景色是白色， -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item style="width: 29%" label="标题">
          <el-input
            style="width: 150%"
            v-model="formInline.w_title"
            placeholder="请输入标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-select
            clearable
            v-model="formInline.w_type"
            placeholder="请选择类型"
          >
            <el-option
              v-for="(item, index) in options"
              :key="index"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            clearable=""
            v-model="formInline.w_state"
            placeholder="请选择"
          >
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onScreen()">筛选</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd()">添加类型</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="tableData"
        style="width: 100%"
        :default-sort="{ prop: 'w_startdate', order: 'descending' }"
      >
        <el-table-column prop="id" label="文章ID" sortable width="140">
        </el-table-column>
        <el-table-column prop="title" label="标题" width="200">
        </el-table-column>
        <el-table-column prop="picture" label="图片" width="200">
          <template slot-scope="scope">
          <el-avatar shape="square" :size="50"  :src="scope.row.picture"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="typeName" label="类型" width="140">
        </el-table-column>
        <el-table-column prop="newDate" label="创建日期" sortable width="200">
        </el-table-column>
        <el-table-column prop="status" label="状态" width="140">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="
                handleSee(scope.$index, scope.row);"
              >查看</el-button
            >
            <el-button
              size="mini"
              type="info"
              @click="
                handleEdit(scope.$index, scope.row);
                dialogFormVisible_1 = true;
              "
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
          </el-main
    >
    <el-main style="padding: 20px 0px">
      <Paging
        @pagesizeChange="getPagesize"
        @currentPageChange="getCurrentPage"
        :total="total"
        :pagesize="pagesize"
        :currentPage="currentPage"
      ></Paging>
          </el-main
    >
    <el-dialog width="70%" title="查看" :visible.sync="dialogTableVisible">
      <el-descriptions class="margin-top" :column="1" border>
        <!-- :size="medium"  -->
        <el-descriptions-item>
          <template slot="label"> 标题 </template>
          {{ InfoData.w_title }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 类型 </template>
          {{ InfoData.w_type }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template prop="image" slot="label"> 封面 </template>
          <el-image
            style="width: 100px; height: 100px"
            :src="InfoData.w_cover"
          ></el-image>
          <!-- 图片的显示 -->
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 状态 </template>
          {{ InfoData.w_state }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 序号 </template>
          {{ InfoData.w_id }}
        </el-descriptions-item>
      </el-descriptions>
      <el-button class="eidt" @click="dialogTableVisible = false"
        >返回</el-button
      >
    </el-dialog>
    <el-dialog width="70%" title="编辑" :visible.sync="dialogFormVisible_1">
      <el-form :model="form">
        <el-form-item label="标题" :label-position="labelPosition">
          <el-input
            placeholder="请输入标题"
            v-model="form.e_title"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-select
            style="width: 100%"
            v-model="form.e_type"
            placeholder="请选择类型"
          >
            <el-option
              v-for="(item, index) in options"
              :key="index"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="原图片">
          <el-image
            style="width: 150px; height: 150px;"
            :src="form.e_picture"
          ></el-image>
        </el-form-item>
         <el-form-item label="封面" :label-position="labelPosition">
          <el-upload
            class="avatar-uploader"
            action="http://121.5.35.178:8081/admin/upload/image"
            list-type="picture-card"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
            :headers="{token:token}"
            name="image"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
             <div class="el-upload__tip" slot="tip">支持格式：JPG/PNG ，单个文件不能超过10MB，建议尺寸：300x400</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" :label-position="labelPosition"
          ><br />
          <el-radio v-model="s_state" :label="1">启用</el-radio>
          <el-radio v-model="s_state" :label="0">禁用</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editCon()">确 定</el-button>
        <el-button @click="noCon()">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog width="70%" title="添加类型" :visible.sync="dialogFormVisible_2">
      <el-form :model="form">
        <el-form-item label="标题" :label-position="labelPosition">
          <el-input
            placeholder="请输入标题"
            v-model="form.a_title"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="类型名称" :label-position="labelPosition"
          ><br />
          <el-select
            style="width: 100%"
            v-model="form.a_type"
            :label-position="labelPosition"
            placeholder="请选择类型"
          >
            <el-option
              v-for="(item, index) in options"
              :key="index"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="封面" :label-position="labelPosition">
          <el-upload
            class="avatar-uploader"
            action="http://121.5.35.178:8081/admin/upload/image"
            list-type="picture-card"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
            :headers="{token:token}"
            name="image"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
             <div class="el-upload__tip" slot="tip">支持格式：JPG/PNG ，单个文件不能超过10MB，建议尺寸：300x400</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="来源" :label-position="labelPosition">
          <el-input
            placeholder="请输入来源"
            v-model="form.a_source"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" :label-position="labelPosition"
          ><br />
          <el-radio v-model="a_state" label="1">启用</el-radio>
          <el-radio v-model="a_state" label="0">禁用</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addCon()">确 定</el-button>
        <el-button @click="dialogFormVisible_2 = false">取 消</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import Pagetitle from "../../components/common/title.vue";
import Paging from "../../components/paging/paging.vue";
export default {
  components: {
    Pagetitle,
    Paging,
  },
  data() {
    return {
      token:'',
      options: [],
      title1: "广告管理",
      title2: "广告内容管理",
      total: 5, //总共多少条，这个需要通过接口获取后赋值
      pagesize: 4, //有4，6，8，10可选,
      currentPage: 1, //当前页数
      formInline: {
        w_itle: "",
        w_type: "",
        w_state: "",
      },
      tableData: [],
      InfoData: [
        {
          w_id: "",
          w_state: "",
          w_type: "",
          w_title: "",
          w_cover: "",//图片
        },
      ],
      form: {
        e_title: "",
        e_type: "",
        e_cover:"",
        a_title: "",
        a_type: "",
      },
      labelPosition: "top",
      s_state: "",
      a_state: "",
      dialogTableVisible: false,
      dialogFormVisible_1: false,
      dialogFormVisible_2: false,
      dialogFormVisible_3: false,
      picture1: "",
      imageUrl:"",
      dialogVisible: false,
      disabled: false,
    };
  },
  //调用
  created() {
    this.getCon(this.currentPage, this.pagesize);
    this.getType();
    this.token=sessionStorage.getItem("token")
  },
  methods: {
    //获取所有数据
    async getCon(page, pagesize) {
      const { data: res } = await this.axios({
        url: "/administration/list",
        method: "post",
        data: {
          title: this.formInline.w_title,
          typeName: this.formInline.w_type,
          status: this.formInline.w_state,
          page: page,
          pageSize: pagesize,
        },
      
      });
      if (res.code == 0) {
        this.total = res.count;
        console.log(res.data);
        this.tableData = res.data;
        // console.log(this.options);
        res.data.forEach((item) => {
          // console.log(item);
          let newTime = this.timeTransfer(item.newDate);
          item.newDate = newTime;
          item.status = this.statusTransfer(item.status);
        });
      }
    },
    //获取所有类型
    async getType() {
      const { data: res } = await this.axios({
        url: "/advertisingType/findbywhere",
        method: "post",
     
      });
      if (res.code == 0) {
        //清空数组
        //  this.options.splice(0,this.options.length)
        this.options = res.data;
      }
    },
    //筛选函数
    async onScreen(index, row) {
      console.log("开始筛选！！！");
      this.getCon(this.currentPage, this.pagesize);
    },
    //添加类型数据
    async addCon() {
      this.dialogFormVisible_2 = false;
      console.log("开始添加！！！");
      const { data: res } = await this.axios({
        url: "/administration/add",
        method: "post",
        data: {
          title: this.form.a_title,
          typeName: this.form.a_type,
          status: this.a_state,
          picture:this.picture1,
        },
       
      });
      if (res.code == 0) {
        this.getCon(this.currentPage, this.pagesize);
        (this.form.a_title = ""),
          (this.form.a_type = ""),
          (this.form.a_source = ""),
          (this.form.a_content = ""),
          (this.a_state = "");
      }
    },
    //查看数据(直接获取此条的数据，不经过服务器)
    handleSee(index, row) {
      this.dialogTableVisible = true;
      console.log(row);
      this.InfoData.w_title = row.title;
      this.InfoData.w_type = row.typeName;
      this.InfoData.w_id = row.id;
      this.InfoData.w_state = row.status;
      this.InfoData.w_cover = row.picture;
    },
    //编辑类型数据
    async editCon() {
      this.dialogFormVisible_1 = false;
      console.log("开始编辑！！！");
      const { data: res } = await this.axios({
        url: "/administration/update",
        method: "post",
        data: {
          title: this.form.e_title,
          type: this.form.e_type,
          cover:this.cover1,
          picture: this.picture1,
          status: this.s_state,
          id: this.id,
        },
       
      });
      if (res.code == 0) {
        this.getCon(this.currentPage, this.pagesize);
        status = this.statusTransfer(this.s_state);
        this.imageUrl='';
      }
    },
    //删除数据
    async delCon(id) {
      const { data: res } = await this.axios({
        url: "/administration/delete/" + id,
        method: "get",
       
      });
      if (res.code == 0) {
        console.log("删除成功！！！");
        this.getCon(this.currentPage, this.pagesize);
      }
      console.log(res.data);
    },

    //子组件传入pagesize
    getPagesize(val) {
      this.pagesize = val;
      this.getCon(this.currentPage, this.pagesize);
    },
    //子组件传入CurrentPage
    getCurrentPage(val) {
      this.currentPage = val;
      this.getCon(this.currentPage, this.pagesize);
    },
    formatter(row, column) {
      return row.address;
    },
    //编辑接口
    handleEdit(index, row) {
      console.log(index, row);
      this.form.e_title = row.title;
      this.form.e_type = row.typeName;
      this.form.e_picture=row.picture;
      this.s_state = row.status == "禁用" ? 0 : 1;
      this.id = row.id;
    },
    noCon() {
      this.dialogFormVisible_1 = false;
      this.getCon(this.currentPage, this.pagesize);
    },
    handleAdd(index, row) {
      console.log(index, row);
      this.dialogFormVisible_2 = true;
    },
    handleDelete(index, row) {
      console.log(index, row);
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.delCon(row.id);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 图片上传
    //图片上传成功的函数
    handleAvatarSuccess(res, file,fileList) {
      this.picture1=res.data;
      this.imageUrl = URL.createObjectURL(file.raw);
      console.log("开始上传!!");
      console.log(res,file,fileList);
    },
    updateData(e = "") {
      let c1 = e.replace(/<img width="100%"/g, "<img");
      let c2 = c1.replace(/<img/g, '<img width="100%"');
      this.content = c2;
      console.log(this.content);
    },
    beforeAvatarUpload(file) {
      let types = ['image/jpeg', 'image/jpg', 'image/gif', 'image/bmp', 'image/png'];
       const isImg = types.includes(file.type);
       if (!isImg) {
          this.$message.error('上传头像图片只能是png、jpg、gif格式!');
        }
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 10MB!");
      }
      return isImg&isLt2M;
    },
    //时间戳的转换
    timeTransfer(timestamp) {
      var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + "-";
      var M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var D =
        (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      var h =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      var m =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      var s =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    },
    //状态转换：数字便文字
    statusTransfer(statusTemp) {
      if (statusTemp == 0) {
        statusTemp = "禁用";
      } else if (statusTemp == 1) {
        statusTemp = "启用";
      }
      return statusTemp;
    },
    //状态转换:文字转数字
    SecstatusTransfer(statusTemp) {
      if (statusTemp == "禁用") {
        statusTemp = 0;
      } else if (statusTemp == "启用") {
        statusTemp = 1;
      }
      return statusTemp;
    },
  },
};
</script>

<style>
.eidt {
  margin-left: 45%;
  margin-top: 5%;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>